package com.edu4java.android.killthemall;

import java.util.Random;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

@SuppressLint("DrawAllocation") public class Sprite {
	// direction = 0 up, 1 left, 2 down, 3 right,
    // animation = 3 back, 1 left, 0 front, 2 right
    int[] DIRECTION_TO_ANIMATION_MAP = { 3, 1, 0, 2 };
	private static final int BMP_ROWS = 4;
	private static final int BMP_COLUMNS = 3;
	private int x ;//o nascimento do sprite sera aleatorio em x e y 
	private int y ;//o nascimento do sprite sera aleatorio em x e y
	private int xSpeed ;
	private int ySpeed ;
	private GameView gameView;
	private Bitmap bmp;
	private int currentFrame = 0;
	private int width;
	private int height;
	
	public Sprite(GameView gameView, Bitmap bmp) {
		this.gameView = gameView;
		this.bmp = bmp;
		this.width = bmp.getWidth() / BMP_COLUMNS;
		this.height = bmp.getHeight() / BMP_ROWS;
		Random rnd = new Random(System.currentTimeMillis());
        xSpeed = rnd.nextInt(50) - 25;// obtem numeros entre -25 e 50 para velocidade
        ySpeed = rnd.nextInt(50) - 25;// obtem numeros entre -25 e 50 para velocidade
        x = rnd.nextInt(gameView.getWidth() - width);//local lancamento sprite aleatorio
        y = rnd.nextInt(gameView.getHeight() - height);//local lancamento sprite aleatorio
	}

	private void update() {
		/* movimento somente lateral eixo x
		 * if (x > gameView.getWidth() - width - xSpeed) { xSpeed = -5; } if (x
		 * + xSpeed < 0) { xSpeed = 5; } x = x + xSpeed;
		 */
		if (x > gameView.getWidth() - width - xSpeed || x + xSpeed < 0) {
			xSpeed = -xSpeed;
		}
		x = x + xSpeed;
		if (y > gameView.getHeight() - height - ySpeed || y + ySpeed < 0) {
			ySpeed = -ySpeed;
		}
		y = y + ySpeed;
		currentFrame = ++currentFrame % BMP_COLUMNS;
	}

	@SuppressLint("DrawAllocation") public void onDraw(Canvas canvas) {
		update();
		int srcX = currentFrame * width;
		int srcY = getAnimationRow() * width; // recebe a linha da funcao
		//int srcY = 1 * height; //escolha da linha 1 da matrix bmp
		Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
		Rect dst = new Rect(x, y, x + width, y + height);
		canvas.drawBitmap(bmp, src, dst, null);
	}
	
	// direction = 0 up, 1 left, 2 down, 3 right,
    // animation = 3 back, 1 left, 0 front, 2 right
    private int getAnimationRow() {
          double dirDouble = (Math.atan2(xSpeed, ySpeed) / (Math.PI / 2) + 2);
          int direction = (int) Math.round(dirDouble) % BMP_ROWS;
          return DIRECTION_TO_ANIMATION_MAP[direction];
    }

	public boolean isCollition(float x2, float y2) {
		//return false;
		return x2 > x && x2 < x + width && y2 > y && y2 < y + height;
	}
}